package com.dddframework.core.contract;

import com.dddframework.core.context.SpringContext;
import com.dddframework.core.context.ThreadContext;
import com.dddframework.core.contract.constant.ContextConstants;
import org.springframework.context.ApplicationEvent;

import java.util.Arrays;
import java.util.Map;

/**
 * 领域事件：解决异步线程变量透传问题
 */
public abstract class DomainEvent extends ApplicationEvent {
    private final Map<String, Object> THREAD_LOCALS = ThreadContext.getValues();

    public <T> DomainEvent(T source) {
        super(source);
    }

    public <T> T get() {
        ThreadContext.setValues(THREAD_LOCALS);
        return (T) super.getSource();
    }

    public boolean tenantIn(String... tenantIds) {
        String tenantId = (String) THREAD_LOCALS.getOrDefault(ContextConstants.TENANT_ID, "");
        return Arrays.asList(tenantIds).contains(tenantId);
    }

    public void publish() {
        SpringContext.getApplicationContext().publishEvent(this);
    }

}
